#include "xge.h"


#include "xatexit_manager.h"
#include "xsys_log.h"
#include "xthread_manager.h"
#include "xconsole.h"
#include "g_graphics.h"
#include "scene_mgr.h"
#include "xfsm.h"

namespace xge{

  using xge_internal::AtExitManager;
  using xge_internal::SystemLog;
  using graphics::CreateGraphics2DDevice;
  using graphics::DestroyGraphics2DDevice;
  using graphics::SceneManager;

  Graphics2D* XGameEngine::kGraphics2DInterface = NULL ;
  FileSystemManager* XGameEngine::kFSManager = NULL;
  SceneManager* XGameEngine::kSceneManager = NULL;
  EventManager* XGameEngine::kEventManager = NULL;
  MainLoop* XGameEngine::kMainLoop = NULL;
  
  bool XGameEngine::CreateGameEngine
    ( size_t width , size_t height , bool fullscreen , 
    const String& caption , const String& icon_res , 
    DeviceType device_type /* = DEVICE_DEFAULT */ ) {
      // 1. Initialize the at exit manager
      if( !AtExitManager::Initialize() ) 
        goto __error;
      // 2. Initialize the system log service
      SystemLog::Initialize();
      // 3. Initialize the thread manager service

      // 4. Initialize the FileSystemManager 
      kFSManager = new FileSystemManager();
      if( !kFSManager->Initialize() ) 
        goto __error;
      // 5. Initialize the renderer service
      kGraphics2DInterface = 
        CreateGraphics2DDevice( NULL , width , height , fullscreen , caption , icon_res , device_type );
      if( kGraphics2DInterface == NULL )
        goto __error;
      // 6. Initialize the resource manager
      // 7. Initialize the scene manager
      kSceneManager = new SceneManager();
      // 8. Initialize the event manager 
      kEventManager = new EventManager();
      // 9. Initialize the main loop
      kMainLoop = new MainLoop(  kEventManager , kSceneManager  );

      return true;
__error:
      if( kFSManager != NULL ) {
        delete kFSManager;
        kFSManager = NULL;
      }
      if( kGraphics2DInterface != NULL ) {
        DestroyGraphics2DDevice(kGraphics2DInterface);
        kGraphics2DInterface=NULL;
      }
      if( kSceneManager != NULL ) {
        delete kSceneManager;
        kSceneManager = NULL;
      }
      if( kEventManager != NULL ) {
        delete kEventManager;
        kEventManager = NULL;
      }
      if( kMainLoop != NULL ) {
        delete kMainLoop ;
        kMainLoop = NULL;
      }
      // log information here
      SYS_LOG(PANIC,true,_xT("XGameEngine can not set up , a error has occur ,see detail in log!"));
      return false;
  }


}// namespace xge